
 <!-- 类目管理 -->
<template>
  <div>
    <div class="block">
      <el-tree :data="data" :props="props" node-key='id' :default-expanded-keys="[...spread]" @node-expand="nodeExpand" @node-collapse="nodeCollapse">
        <span class="custom-tree-node" slot-scope="{node,data}">
          <div class="box">
            <el-image style="width: 30px; height: 30px" :src="data.picUrl" v-if="data.level==2"></el-image>
            <span>{{ node.label }}</span>
            <el-tag v-if="data.level!=-1" :type="data.level==0?'danger':data.level==1?'warning':'success'">{{data.level==0?'一级':data.level==1?'二级':'三级'}}</el-tag>
          </div>
          <span>
            <el-button type="primary" size="mini" round v-if="data.level!=2" @click="addAdmin(data)" v-permission="'product:category:create'">添加</el-button>
            <el-button type="warning" size="mini" round v-if="data.level!=-1" @click="handleEdit(data)" v-permission="'product:category:edit'">编辑</el-button>
            <el-button type="danger" size="mini" round v-if="!data.childrenList" @click="handleDelete(data)" v-permission="'product:category:delete'">删除</el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <!-- 添加--编辑弹框 -->
    <el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="类目名称" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入类目名称"></el-input>
        </el-form-item>
        <el-form-item label="类目图片" prop="picUrl">
          <el-upload class="avatar-uploader" :headers="headers" action="/upload/admin" list-type="picture-card" :show-file-list="false" :on-success="onSuccess" :before-upload="beforeUpload">
            <img v-if="ruleForm.picUrl" :src="ruleForm.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="dialogTableVisible=false"> 取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import cookie from "js-cookie";
import Apiadmin from "../../api/admin"
export default {
  data() {
    return {
      spread: [0], // 存储展开的数据
      data: [],  //树形数据
      props: {   //配置项
        label: 'title',  //指定节点标签为节点对象的某个属性值
        children: 'childrenList'  //指定子树为节点对象的某个属性值
      },
      title: '', //弹框标题添加或编辑
      dialogTableVisible: false, //弹框显示或隐藏
      // 表单数据
      ruleForm: {
        title: '', //类目标题
        parentId: '', //类目父节点
        // iconUrl: '', //类目图标
        picUrl: '', //类目图片
      },
      headers: {  //上传图片请求token
        AdminToken: cookie.get('AdminToken')
      },
      // 表单验证
      rules: {
        title: [
          { required: true, message: '请输入类目名称', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.categoryList()
  },

  methods: {
    // 请求树形数据
    categoryList() {
      Apiadmin.categoryTree().then(res => {
        this.data = [{
          title: '全部分类',
          childrenList: [...res.data],
          level: -1,   //隐藏tag标签
          id: 0,
        }]
      })
    },
    //上传图片方法
    //成功时触发事件
    onSuccess(res) {
      // console.log(res)
      if (res.errno == 200) {
        this.ruleForm.picUrl = res.url;  //上传图片成功的路径
        this.categoryList()
      }
    },
    //选择确定时触发
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/JPEG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      return isLt2M;
    },
    // 节点被展开时触发的事件
    nodeExpand(data, node, e) {
      // console.log(data,node,e);
      this.spread.push(data.id);
    },
    // 节点被关闭时触发的事件
    nodeCollapse(data, node, e) {
      const index = this.spread.findIndex(item => item === data.id);
      this.spread.splice(index, 1);
    },
    // 添加按钮
    addAdmin(row) {
      this.ruleForm = {}   //清空表单
      console.log(row)
      this.title = '添加'
      this.dialogTableVisible = true
      this.ruleForm.parentId = row.id
      // 解决添加出现验证提示之后关闭弹出框,点击编辑发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },
    // 编辑按钮
    handleEdit(row) {
      console.log(row)
      this.title = '编辑'
      this.dialogTableVisible = true
      this.ruleForm = JSON.parse(JSON.stringify(row))
      // 解决编辑出现验证提示之后关闭弹出框,点击添加发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },
    //添加--编辑提交按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == '添加') {
            Apiadmin.categorytAdd(this.ruleForm).then(res => {
              console.log(res)
              if (res.errno == 200) {
                this.dialogTableVisible = false
                this.categoryList() //刷新页面
                this.ruleForm = {} //清空表单
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "添加失败",
                  type: 'error'
                });
              }
            }).catch(err => {
              console.log(err)
            })
          }
          if (this.title == '编辑') {
            Apiadmin.categoryEdit(this.ruleForm).then(res => {
              console.log(res)
              if (res.errno == 200) {
                this.$message({
                  message: "编辑成功",
                  type: 'success'
                });
                this.dialogTableVisible = false
                this.categoryList()  //刷新页面
                this.ruleForm = {}    //清空表单
              } else {
                this.$message({
                  message: "编辑失败",
                  type: 'error'
                });
              }
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除
    handleDelete(row) {
      console.log(row)
      Apiadmin.categoryDelete({ id: row.id }).then(res => {
        console.log(res)
        if (res.errno == 200) {
          this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(res => {
            this.categoryList()   //刷新页面
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(err => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          })
        }
      })
    },
    //去除表单验证
    resetForm(formName) {
      //clearValidate方法为移除表单的校验结果          //resetFields(); //移除校验结果并重置字段值
      this.$refs[formName].clearValidate();          //clearValidate(); //移除校验结果
    },
  }
};
</script>

<style scoped  lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.box {
  span {
    margin-right: 12px;
  }
}
.el-image {
  vertical-align: middle;
  margin-right: 10px;
}
/deep/.el-tree-node__content {
  height: 50px;
}
/deep/.el-tree-node__expand-icon {
  margin-right: 10px;
}
</style>

